package com.qunar.toku;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.qunar.toku.proxy.ServiceProxy;


public class TokuInit {
	
	protected static String DEFAULT_CONFIG_PATH = null;
	
	static {
		DEFAULT_CONFIG_PATH = System.getProperty("toku.client.config.path");
    	if(DEFAULT_CONFIG_PATH == null) {
    		DEFAULT_CONFIG_PATH = System.getProperty("toku.config.path");
    	}
    	
    	if(DEFAULT_CONFIG_PATH == null) {
    		DEFAULT_CONFIG_PATH = getJarPath(TokuConst.class) + "/toku.config";
    	}
    	
    	registerExcetEven();
	}
	
	private static String getJarPath(Class<?> type) {
        String path = type.getProtectionDomain().getCodeSource().getLocation().getPath();
        path = path.replaceFirst("file:/", "");
        path = path.replaceAll("!/", "");
        path = path.replaceAll("\\\\", "/");
        path = path.substring(0, path.lastIndexOf("/"));
        if (path.substring(0, 1).equalsIgnoreCase("/")) {
            String osName = System.getProperty("os.name").toLowerCase();
            if (osName.indexOf("window") >= 0) {
                path = path.substring(1);
            }
        }
        try {
            return URLDecoder.decode(path, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(TokuConst.class.getName()).log(Level.SEVERE, null, ex);
            return path;
        }
    }

	public static void init(String configPath) {
		
		TokuConst.CONFIG_PATH = DEFAULT_CONFIG_PATH = configPath;
	}
	
	
	private static void registerExcetEven() {
		Runtime.getRuntime().addShutdownHook(new Thread() {
			public void run() {
				ServiceProxy.destroyAll();
			}
		});
	}

}
